package com.lagou.rocket.service;

import com.lagou.rocket.dao.OrderDao;
import com.lagou.rocket.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class OrderService {


    @Resource
    private WarehouseService warehouseService;
    @Resource
    private OrderDao orderDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public String submitOrder(String goods, Integer num) {
        Order order = new Order();
        order.setName(goods);
        order.setStatus(1);
        String id = UUID.randomUUID().toString();
        order.setNum(num);
        order.setId(id);
        // 尝试减库存

        if (!warehouseService.hasStock(goods, num)) {
            log.info("库存不足");
            return null;
        }
        log.info("发送订单，id:"+order.getId());
        rocketMQTemplate.convertAndSend("mq-order-lagouphone", order);
        return id;
    }

    public Boolean pay(String id) {
        return redisTemplate.delete("order:" + id);
    }

    public Order get(String id) {
        String s = redisTemplate.opsForValue().get("order:" + id);
        if (s == null || s.isEmpty()) {
            log.info("订单处理中...");
            return null;
        }
        return getOrder(id);
    }

    public Order getOrder(String id) {
        return orderDao.findById(id).get();
    }

    public List<Order> listOrder() {
        Order probe = new Order();
        probe.setStatus(1);
        return orderDao.findAll(Example.of(probe));
    }


    public boolean createOrder(Order order) {
        Optional<Order> byId = orderDao.findById(order.getId());
        if (byId.isPresent()){
            return false;
        }
        orderDao.save(order);
        redisTemplate.opsForValue().set("order:" + order.getId(), "", 60, TimeUnit.SECONDS);
        return true;
    }

    public void invalidOrder(String id) {
        Order orderInfo = orderDao.findById(id).get();
        orderInfo.setStatus(0);
        orderDao.save(orderInfo);
    }


}
